layui.define(['layer','my_jq_upload'], function (exports) {
    var $ = layui.$, tamp = new Date().getTime();
    var elem = '#enian_menu_' + tamp, func = {};
    var init_ed = 0;//初始化
    var my_jq_upload = layui.my_jq_upload;

    function init(arg) {
        console.log('初始化')
        var uploadUrl = arg.uploadUrl
            , fileBoxElemId = arg.fileBoxElemId
            , fileButtonElemId = arg.fileButtonElemId
            , fileAddElemId = arg.fileAddElemId //添加文件的容器
            , uploadList=[];



        
        var oFileList = $(".fileList");					//表格tbody
        var sizeObj = [];								//存放每个文件大小的数组，用来比较去重

        // 上传文件初始化
        my_jq_upload.init({
            uploadUrl: "{:url('api/file/upload')}",
            fileBoxElemId: 'checkImgWindow',
            fileAddElemId: 'upload_file',
            getFile: function (fileList) {
                console.log('得到文件');
                // console.log(fileList);
                if (fileList.length == 0) {
                    layer.msg('取消上传');
                    return;
                }
                var path=arg.getUploadPath();
                publicUpload(fileList, path);
            }
        })

        // 监听上传文件的input
        $('#' + fileAddElemId).change(function (x) {
            console.log('文件选择结束');
            console.log($(this).prop('files'));
            var fileList = $(this).prop('files');
            var path = $(this).data('upload_path');
            publicUpload(fileList, path);

        })

        function publicUpload(fileList,path){
            
            console.log(fileList);
            if (fileList.length == 0) {
                // layer.msg('未选择上传文件');
                return;
            }
            for (let i = 0; i < fileList.length; i++) {
                start = 0;
                end = fileLength + start;
                var identification = new Date().getTime() + '' + Math.round(Math.random() * 9000);
                fileList[i]['identification'] = identification;
                fileList[i]['elemname'] = identification;
                fileList[i]['cloudpath'] = path;
                fileList[i]['finish'] = 0;
                fileList[i]['uploadStatus'] = 0;// 0.排队 1.正在传输
                fileList[i]['uploadStart'] = 0;// 开始
                fileList[i]['uploadEnd'] = 0;// 结束
                fileUploadList[identification] = fileList[i];
                createItem(identification, path, fileList[i]['name'], bytesToSize(fileList[i]['size']));
                // up(fileList[i], start, end);
                // break;
            }

            // 选择完直接上传
            // console.log(7878);
            showUploadList()
            upfile();
        }

        // ============== 新上传代码 ================

        var xhr = new XMLHttpRequest();
        var fd;
        var fileLength = 5 * 1024 * 1024;// 分段大小 5M
        var fileUploadList = {};
        var start, end, blob, pecent, filename;
        

        function checkUploadList(){
            for (const key in fileUploadList) {
                const element = fileUploadList[key];
                // console.log(element);
                if (element.uploadStatus == 0) {
                    start_upload(element);
                    break;
                }
            }
        }


        // 上传文件
        function upfile() {
            var uploadDing = 0;//是否正在传输
            // var haveUploading=0;
            // if (uploadDing==0){
            console.log("正在传输列表");
            console.log(fileUploadList);
            var will_start_element = null;//将要启动的对象
            var will_start_tag = null;//将要启动标识

            for (const key in fileUploadList) {
                const element = fileUploadList[key];
                // console.log(element);
                if (element.uploadStatus == 0) {
                    if (!will_start_tag){
                        will_start_tag=1
                        will_start_element = element;
                    }
                    // break;
                }

                // 如果有正在传输的将will_start_element设为空，永远保留一个上传
                if (element.uploadStatus == 1) {
                    will_start_tag=null;
                    break;
                }
            }
            if (will_start_tag){
                start_upload(will_start_element);
            }
            
        }

        // 开始传输
        function start_upload(file) {
            // console.log(file);
            var start=file.uploadStart;
            var end=file.uploadEnd;
            var num = $('.progressNum-' + file.elemname);
            var tr = $('#tr-' + file.elemname);
            var operation_start = $('#operation_start_' + file.elemname);
            tr.data('status', 1);
            if (file.uploadStatus==2){
                return;
            }
            file.uploadStatus =1;
            if (start < file.size) {
                xhr.open('POST', '/api/file/upload', true);
                xhr.setRequestHeader("Token", app.getToken())
                //xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.onreadystatechange = function () {
                    if (this.readyState == 4) {
                        // console.log('上传结果', this);
                        if (this.status >= 200 && this.status < 300) {
                            // console.log(this.responseText);
                            if (this.responseText) {
                                data = JSON.parse(this.responseText);
                                // console.log('上传结果', data);
                                if (data.err_code === 0) {
                                    num.html('上传完成')
                                    tr.remove();//删除dom项目
                                    var rfile = {};
                                    rfile = file;
                                    delete (fileUploadList[file.elemname]);

                                    // 此处上传完成回调函数
                                    if (arg.uploadSuccess) {
                                        arg.uploadSuccess(rfile);
                                    }
                                    upfile()
                                } else {
                                    // 上传出错，增加重传按钮
                                    num.html(data.err_msg);
                                    operation_start.text('重新上传');
                                    tr.data('status',-1);
                                    file.uploadStatus = -1;
                                    console.log('上传错误', data.err_msg);
                                }
                                // des.style.width = '0%';
                            } else {
                                start = end;
                                end = start + fileLength;
                                // 记录上传位置
                                file.uploadStart = start;
                                file.uploadEnd = end;
                                start_upload(file);
                            }
                        }
                    }
                }
                xhr.upload.onprogress = function (ev) {
                    // console.log(ev);
                    if (ev.lengthComputable) {
                        pecent = 100 * (ev.loaded + start) / file.size;
                        console.log('文件上传中 ' + file.name, file.uploadStatus);
                        if (pecent >= 100) {
                            pecent = 99.99;
                        }
                        num.html(pecent.toFixed(2) + '%');
                    }
                }

                //分割文件核心部分slice
                blob = file.slice(start, end);
                fd = new FormData();
                fd.append('mof', blob);
                fd.append('filename', file.name);
                fd.append('filesize', start + '-' + end + '/' + file.size);
                fd.append('size', end - start);
                fd.append('num', (end / fileLength) + '/' + Math.ceil(file.size / fileLength))
                fd.append('identification', file.identification);
                fd.append('path', file.cloudpath);
                //console.log(fd);
                //pending=true;
                xhr.send(fd);
                
            } else {
                //clearInterval(clock);
            }
        }

        function createItem(identification, path, name, volume, c) {
            var p_id = 0;
            var oFileList_parent = $(".fileList_parent");	//表格
            var oFileList = $(".fileList");					//表格tbody
            var oFileBtn = $("#fileBtn");					//上传按钮

            uploadList.push();

            var oTr = $("<tr id='tr-" + identification + "' data-status='0' data-index='" + identification + "' data-identification='" + identification +"'></tr>");
            var str = '<td id="td-' + identification + '" data-index="' + identification + '" class="upload-file-info" data-finsh=0 data-path="' + path + '" data-p_id="' + p_id + '"><cite title="' + name + '"></cite>' + name + " (" + volume+")"+ '</td>';
            // str += '<td>'+ type +'</td>';
            // str += '<td>' + volume + '</td>';
            // str += '<td><input type="radio" /></td>';
            str += '<td>';
            str += '<div class="progressParent">';
            str += '<p class="progress"></p>';
            str += '<span class="progressNum-' + identification + '" >等待传输</span>';
            str += '</div>';
            str += '</td>';
            str += '<td><a href="javascript:;" class="operation_del layui-hide" id="operation_del_' + identification + '">删除</a>  <a href="javascript:;" style="color:#1e9fff" id="operation_start_' + identification +'">暂停</a></td>';
            
            oTr.html(str);
            oTr.appendTo(oFileList);

            // //删除表格行
            // $('#operation_del_' + identification).click(function () {
            //     var oTr = $(this).parents("tr");
            //     console.log($(this));
            //     var index = oTr.index();
            //     oTr.remove();
            // });

            // 监听开始
            $('#operation_start_' + identification).click(function () {
                // var oTr = $(this).parents("tr");
                console.log($(this).attr('id'));
                var index=$(this).parent().parent().data('index');
                console.log($(this).parent().parent().data('index'));
                // return;

                // console.log(fileUploadList[index]);
                console.log('打开传输', index, fileUploadList[index].uploadStatus);
                // 如果文件状态为待传输或者正在传输状态
                if (fileUploadList[index].uploadStatus == 0 || fileUploadList[index].uploadStatus == 1){
                    fileUploadList[index].uploadStatus = 2;
                    console.log('文件停止传输', fileUploadList[index].name);
                    $(this).text('继续');
                    upfile();
                } else if (fileUploadList[index].uploadStatus == -1) {
                    $(this).text('暂停');
                    console.log('文件重新传输', fileUploadList[index].name);
                    fileUploadList[index].uploadStatus = 0;
                    fileUploadList[index].uploadStart=0;
                    fileUploadList[index].uploadEnd=0;
                    // 重设identification
                    fileUploadList[index].identification=new Date().getTime() + '' + Math.round(Math.random() * 9000);
                    console.log('文件重新传输状态', fileUploadList[index].uploadStatus);
                    upfile();
                }else {
                    $(this).text('暂停');
                    console.log('文件恢复传输', fileUploadList[index].name);
                    fileUploadList[index].uploadStatus = 0;
                    upfile();
                }
                
                
            });

        }

        // ================= 新上传代码 ================

    }


    function init_layer(arg) {
        if (init_ed == 1) {
            init(arg)
            return;
        }
        var html =
            '<div class="" style="height: 55px;line-height: 55px;background:#f2f2f2">'
            + '<div class="layui-inline upload_window_title" style="margin-left: 20px;width:75%"> 正在传输</div>'
            + '<div id="upload-layer-btn-close" class="layui-inline" style="float: right;margin-right: 20px"><i class="layui-icon layui-icon-close" style="font-size: 20px;cursor: pointer;"></i></div>'
            + '</div>'

        html += '<table width="50%" class="fileList_parent layui-table" lay-size="sm" lay-skin="line">'
        html += '<thead><tr>'
        html += '<th>文件名</th>'
        // html+='<th>类型</th>'
        // html += '<th>大小</th>'
        // html+='<th>私藏</th>'
        html += '<th>进度</th>'
        html += '<th>操作</th>'
        html += '</tr></thead>'
        html += '<tbody class="fileList">'
        html += '</tbody>'
        html += '</table>'



        layer.open({
            type: 1,
            title: false,
            move:'.upload_window_title',
            // offset: 'rb', //右下角弹出
            // skin: 'layui-layer-demo', //样式类名
            closeBtn: 0, //不显示关闭按钮
            anim: 2,
            area: ['300px', '300px'],
            shade: false,
            content: html,
            success: function () {
                console.log('创建完成');
                init_ed = 1
                $('#upload-layer-btn-close').parent().parent().parent().hide()
                init(arg)
                $('#upload-layer-btn-close').click(function () {
                    $(this).parent().parent().parent().hide()
                })
            }
        });
    }

    // //字节大小转换，参数为b
    function bytesToSize(bytes) {
        var sizes = ['B', 'KB', 'MB', 'GB'];
        if (bytes == 0) return 'n/a';
        var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
    };

    //通过文件名，返回文件的后缀名
    function fileType(name) {
        var nameArr = name.split(".");
        return nameArr[nameArr.length - 1].toLowerCase();
    }

    function showUploadList() {
        $('#upload-layer-btn-close').parent().parent().parent().show()
    }
    function hideUploadList() {
        $('#upload-layer-btn-close').parent().parent().parent().hide()
    }
    

    var jq_upload = {
        init: init_layer,
        analysisList: function (file) {
            func.analysisList(file)
        },
        showUploadList: showUploadList,
        hideUploadList: hideUploadList,
        dragWindowShow: function () { func.oFileSpanShow() },
        dragWindowHide: function () { func.oFileSpanHide(); console.log('隐藏上传列表窗口') }
    }


    exports('my_upload', jq_upload);
});    
